package org.jeecg.modules.client;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.google.gson.JsonObject;
import io.netty.util.Constant;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 月月鸟
 */
@Component
public class GetuiPush {
    public String BaseUrl  = "https://restapi.getui.com/v2/";
    @Value("${application.getuiAppId}")
    public String appId;
    @Value("${application.getuiAppKey}")
    public String appKey;
    @Value("${application.getuiAppSecret}")
    public String appSecret;
    @Value("${application.getuiMasterSecret}")
    public String masterSecret;

    @Autowired
    private RedisUtil redisUtil;
    public static String Token;
    /**
     * 获取鉴权token
     * */
    public String getToken(){
        String timestamp = String.valueOf(new Date().getTime());
        String url = BaseUrl+appId+"/auth";
        String sign = getSHA256(appKey + timestamp + masterSecret);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sign",sign);
        jsonObject.put("timestamp",timestamp);
        jsonObject.put("appkey",appKey);
        String post = HttpUtil.post(url, jsonObject.toString());
        JSONObject reqJson = new JSONObject(post);
        int code = (int) reqJson.get("code");
        if (code == 0 ){
            JSONObject data = new JSONObject(reqJson.get("data"));
            Token=(String) data.get("token");
            return (String) data.get("token");
        }else {
            return null;
        }
    }

    /**
     * cid cid数组，只能填一个cid
     * transmission 纯透传消息内容，安卓和iOS均支持 ,长度 ≤ 3072
     * */
    public void PushMsg(String phone,String transmission){
        String url = BaseUrl+appId+"/push/single/cid";
        System.out.println(url);
        String requestId = RandomUtil.randomString(30);
        String key = "client_id_prefix"+phone;
        String typeKey = "client_id_prefix"+"type"+phone;
        boolean b = redisUtil.hasKey(key);
        boolean c = redisUtil.hasKey(typeKey);
        if (b&&c){
            String cid = (String) redisUtil.get(key);

            String type = (String) redisUtil.get(typeKey);//1.安卓 2.ios
            if (StringUtils.isEmpty(Token)){
                getToken();
            }
            //主体
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("request_id",requestId);
            //cid
            JSONObject audience = new JSONObject();//https://docs.getui.com/getui/server/rest_v2/push/
            List<String> a = new ArrayList<>();
            a.add(cid);
            audience.put("cid", a);
            jsonObject.put("audience",audience);
            //个推推送消息参数
            JSONObject pushMessage = new JSONObject();
            //消息配置
            JSONObject settings = new JSONObject();
            JSONObject strategy = new JSONObject();
            strategy.put("default", 1);
            settings.put("strategy", strategy);
            settings.put("ttl", -1);
            jsonObject.put("settings",settings);
            //通知消息内容
            if (type.equals("1")){
                //通知消息内容，仅支持安卓系统
                JSONObject notification = new JSONObject();
                notification.put("title","系统消息");//通知消息标题，长度 ≤ 50
                notification.put("body",transmission);//通知消息内容，长度 ≤ 256
                //点击通知后续动作，
                //目前支持以下后续动作，
                //intent：打开应用内特定页面，
                //url：打开网页地址，
                //payload：自定义消息内容启动应用，
                //payload_custom：自定义消息内容不启动应用，
                //startapp：打开应用首页，
                //none：纯通知，无后续动作
                notification.put("click_type","none");
                pushMessage.put("notification", notification);
            }else if (type.equals("2")){
                //纯透传消息内容，安卓和iOS均支持
                pushMessage.put("transmission", transmission);
                //厂商推送消息参数
                JSONObject pushChannel = new JSONObject();
                //ios厂商通道消息
                JSONObject ios = new JSONObject();
                ios.put("type","notify");//notify默认通知消息
                //推送通知消息内容
                JSONObject aps = new JSONObject();
                aps.put("content-available",0);//0表示普通通知消息(默认为0)
                //通知消息
                JSONObject alert = new JSONObject();
                alert.put("title","系统消息");//通知消息标题
                alert.put("body",transmission);//通知消息内容
                aps.put("alert",alert);
                ios.put("aps",aps);
                pushChannel.put("ios",ios);
                jsonObject.put("push_channel",pushChannel);//厂商推送消息参数
            }
            jsonObject.put("push_message",pushMessage);
            String rsp = HttpRequest.post(url)
                    .header("token", Token)
                    .body(jsonObject.toString())
                    .execute().body();
            System.out.println(jsonObject.toString());
            System.out.println(rsp);
        }
    }
    /**
     * 利用java原生的类实现SHA256加密
     *
     * @param str 参数拼接的字符串
     * @return
     */
    public static String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }
    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String temp = null;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                sb.append("0");
            }
            sb.append(temp);
        }
        return sb.toString();
    }
}
